package com.eh.session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * Created by David Li on 2016/5/19.
 */
@WebServlet("/cookie.member.do")
public class CookieMemberServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = (String) req.getAttribute("username");
        if (username == null) {
            // 尝试从缓存中取
            Cookie[] cookies = req.getCookies();
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals("username") && "david".equals(cookie.getValue())) {
                    req.setAttribute("username", cookie.getValue());
                    req.getRequestDispatcher("/WEB-INF/session/cookieServletMember.jsp").forward(req, resp);
                    return;
                }
            }
        }

        if ("david".equals(username)) {
            req.getRequestDispatcher("/WEB-INF/session/cookieServletMember.jsp").forward(req, resp);
            return;
        }
        resp.sendRedirect("/servlet/cookieServletLogin.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
